<template>
    <view>
        <view>
            <form>
                <view class="cu-form-group margin-top">
                    <view class="title">组织名称</view>
                    <input @input="Input" :value="association.association_name" data-field="association_name" placeholder="计科青协" />
                </view>
                <view class="cu-form-group">
                    <view class="title">归属学院</view>
                    <picker class="form-input" mode="selector" :range="collegeList" :value="index" @change="collegeChange">
                        {{ association.college_name === undefined ? '请选择归属学院' : association.college_name }}
                    </picker>
                </view>
                <view class="cu-bar bg-white margin-top">
                    <view class="action">LOGO上传</view>
                    <view class="action">{{ imgList.length }}/1</view>
                </view>
                <view class="cu-form-group">
                    <view class="grid col-4 grid-square flex-sub">
                        <view class="bg-img" @tap="ViewImage" :data-url="imgList[index]" v-for="(item, index) in imgList" :key="index">
                            <image :src="imgList[index]" mode="aspectFill"></image>

                            <view class="cu-tag bg-red" @tap.stop.prevent="DelImg" :data-index="index">
                                <text class="cuIcon-close"></text>
                            </view>
                        </view>
                        <view class="solids" @tap="ChooseImage" v-if="imgList.length === 0">
                            <text class="cuIcon-cameraadd"></text>
                        </view>
                    </view>
                </view>
                <view class="cu-form-group align-start">
                    <view class="title">描述</view>
                    <textarea maxlength="-1" :value="association.description" @input="Input" data-field="description" placeholder="内容"></textarea>
                </view>
                <view class="flex justify-center">
                    <button class="cu-btn bg-blue shadow-blue margin" style="width: 80%;" @tap="Edit">
                        修改
                    </button>
                </view>
            </form>
        </view>
        <view>
            <view class="flex justify-end">
                <view class="flex-xl">
                </view>
                <view class="flex-xs">
                    <button @click="delDepartment" class="cu-btn radius margin-right shadow bg-red">删除部门</button>
                </view>
            </view>
            <view class="flex justify-end align-center">
                <view class="flex-xl">
                    <input type="text" :value="addDepartName" @input="inputDepartment" class="round padding bg-white solid-bold" style="height: 48px;" placeholder="新增部门名称" />
                </view>
                <view class="flex-xs">
                    <button @click="addDepartment" class="cu-btn margin radius shadow bg-green">新增部门</button>
                </view>
            </view>


            <view class="uni-container padding">
                <uni-table
                    ref="table"
                    :loading="loading"
                    border
                    stripe
                    type="selection"
                    emptyText="暂无更多数据"
                    @selection-change="selectionChange">
                    <uni-tr>
                        <uni-th align="center">部门名称</uni-th>
                    </uni-tr>
                    <uni-tr v-for="(item, index) in departmentList" :key="index">
                        <uni-td>{{ item.department_name }}</uni-td>
                    </uni-tr>
                </uni-table>
                <view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total" @change="change" /></view>
            </view>
        </view>
    </view>
</template>

<script>
const app = getApp();

export default {
    data() {
        return {
            //图片列表
            imgList:[],
            //组织数据
            association: {
                association_name: '',
                logo: '',
                description: '',
                association_id: '',
                college_name: '',
            },
            //学院列表
            collegeList: [{
                college_id: '',
                college_name: ''
            }],
            //学院数据
            collegeDetail:[],
            departmentList: [{
                department_id: '',
                department_name: ''
            }],
            //学院索引
            index: -1,
            loading: false,
            addDepartName: '',
            id:-1,
            pageSize: 0,
            pageCurrent: 1,
            total: 0,
        };
    },
    onLoad: function (options) {
        this.id = options.id;
        this.getCollegeList();
        this.getAssociation();
        this.getDepartment();
    },
    onBackPress(e) {
        uni.reLaunch({
            url: '../../pages/association/detail/detail?id=' + this.id
        });
    },
    onPullDownRefresh: function () {
        this.getCollegeList();
        this.getAssociation();
        this.getDepartment();
        uni.stopPullDownRefresh();
    },
    methods: {

        /**
         * 获取学院数据
         */
        getCollegeList() {

            this.$myFunction.getData(app.globalData.ApiUrl + 'api/Android/getCollegeList', {
                SafeCode: uni.getStorageSync('SafeCode')
            }).then(res => {
                this.collegeDetail = res.data;
                let college = [];
                for (let i = 0; i < res.data.length; i++) {
                    college.push(res.data[i].college_name);
                }
                this.collegeList = college;
            });
        },
        /**
         * 获取组织数据
         */
        getAssociation() {

            const that = this;

            this.$myFunction.getData(app.globalData.ApiUrl + 'api/Android/getAssociationDetail', {
                SafeCode: uni.getStorageSync('SafeCode'),
                association_id: this.id
            }).then(res => {
                console.log(res);
                this.association = res.data;


                //将logo下载到本地
                uni.downloadFile({
                    url: res.data.logo,
                    success: (res1) => {
                        uni.saveImageToPhotosAlbum({ // 然后调用这个方法
                            filePath: res1.tempFilePath,
                            success: (res2) => {
                                console.log(res2);
                                that.setData({
                                    imgList: [res2.file]
                                })
                            }
                        })

                    }
                });

            });
        },

        /**
         * 输入新增部门名称
         */
        inputDepartment(e) {
            this.addDepartName = e.detail.value;
            console.log(this.addDepartName);
        },
        /**
         * 输入框输入事件
         */
        Input(e) {
            let field = 'association.' + e.currentTarget.dataset.field;
            let value = e.detail.value;
            this.setData({
                [field]: value
            });

            console.log(this.association);
        },

        /**
         * 选择图片
         */
        ChooseImage:function () {
            let that = this;
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    that.setData({
                        imgList:[res.tempFilePaths[0]],
                    })
                }
            });
        },
        /**
         * 预览图片
         **/
        ViewImage:function (e) {
            uni.previewImage({
                urls: this.imgList,
                current: e.currentTarget.dataset.url
            });
        },
        /**
         * 删除图片
         **/
        DelImg:function (e) {
            let that = this;
            that.setData({
                imgList:[]
            })
        },

        /**
         * 修改学院
         */
        collegeChange(e) {
            let college_id = this.collegeDetail[e.detail.value].college_id;
            let college_name = this.collegeDetail[e.detail.value].college_name;

            this.setData({
                'association.college_id': college_id,
                'association.college_name': college_name,
            });

        },
        /**
         * 提交申请
         */
        Edit() {
            let association = this.association;
            let imgList = this.imgList;

            //上传图片，附加数据
            if (imgList.length <= 0) {
                uni.showToast({
                    title: '请上传图片',
                    icon: 'none'
                });
                return;
            }
            uni.showLoading({
                title: '正在提交',
                mask: true
            });
            uni.uploadFile({
                url: app.globalData.ApiUrl + 'api/Android/applyAssociation',
                filePath: imgList[0],
                name: 'logo',
                formData: {
                    'SafeCode': uni.getStorageSync('SafeCode'),
                    'association': JSON.stringify(association),
                    'association_id': this.id,
                    //传入edit，表示是修改
                    'edit': 1
                },
                success: function (res) {

                    console.log(res.data);

                    let data = JSON.parse(res.data);
                    uni.hideLoading();
                    if (data.code == 1) {
                        uni.showToast({
                            title: data.msg,
                            icon: 'none'
                        });
                    }else {
                        uni.showToast({
                            title: data.msg,
                            icon: 'none'
                        });
                    }
                }
            });
        },
        /**
         * 新增部门
         * @returns {*}
         */
        addDepartment() {
            this.$myFunction.getData(
                app.globalData.ApiUrl + 'api/Android/addAssociationDepartment', {
                    SafeCode: uni.getStorageSync('SafeCode'),
                    association_id: this.id,
                    department_name: this.addDepartName
                }).then(res => {
                    console.log({
                        'SafeCode': uni.getStorageSync('SafeCode'),
                        'association_id': this.id,
                        'department_name': this.addDepartName
                    });
                    console.log(res);
                    if (res.code == 1) {
                        this.addDepartName = '';
                        uni.showToast({
                            title: '新增成功',
                            icon: 'none'
                        });
                        this.getDepartment();
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
             });
        },
        /**
         * 删除部门
         * @returns {*}
         */
        delDepartment() {
            let deleteList = this.selectedItems();
            if (deleteList.length <= 0) {
                uni.showToast({
                    title: '请选择要删除的部门',
                    icon: 'none'
                });
                return;
            }

            this.$myFunction.getData(
                app.globalData.ApiUrl + 'api/Android/deleteAssociationDepartment', {
                    SafeCode: uni.getStorageSync('SafeCode'),
                    association_id: this.id,
                    delList:deleteList
                }).then(res => {

                    console.log(res);

                    if (res.code == 1) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'none'
                        });
                        this.getDepartment();
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });

        },
        /**
         * 获取部门列表
         * @returns {*}
         */
        getDepartment() {
            this.$myFunction.getData(
                app.globalData.ApiUrl + 'api/Android/getAssociationDepartmentList', {
                    SafeCode: uni.getStorageSync('SafeCode'),
                    association_id: this.id
                }).then(res => {

                    console.log("获取部门数据")
                    console.log(res);

                    if (res.code == 1) {
                        this.departmentList = res.data;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });

        },
        // 多选处理
        selectedItems() {
            return this.selectedIndexs.map(i => this.departmentList[i])
        },
        // 多选
        selectionChange(e) {
            console.log(e.detail.index)
            this.selectedIndexs = e.detail.index
        },
        // 分页触发
        change(e) {
            this.$refs.table.clearSelection()
            this.selectedIndexs.length = 0
        }
}
};
</script>
<style>
*{
    /*border: solid 1px #ccc;*/
}
</style>
